package com.cqc.jdk8.Jnio.file;

import com.cqc.jdk8.Jnio.file.attribute.MySimpleFileVisitor;
import org.junit.Test;

import javax.activation.MimetypesFileTypeMap;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.LinkedList;
import java.util.List;

/**
 * @author cui
 * @description T
 * @date 2022/6/8
 **/
public class FilesTest {

    //创建目录
    @Test
    public void f1() throws IOException {
//        Path path = Paths.get("D:/", "temp", "A", "B", "C", "a.txt");
////        //创建多级目录,已经存在再次创建不会报错，也不会再次创建
//        Path dirPah = Files.createDirectories(path);
////        //path转String  D:\temp\A\B\C\a.txt  注意： "a.txt"是目录，不是文件
//        System.out.println(dirPah.toString());
//
//
//        //只能创建一级目录,如果创建多级，且不存在，就报错 java.nio.file.NoSuchFileException: D:\temp\B
//        // (已经存在的目录不能再次创建)java.nio.file.FileAlreadyExistsException: D:\B
////        Path dir2 = Files.createDirectory(Paths.get("D:/","temp", "B"));

        //已经存在不能创建  FileAlreadyExistsException
        Path path2 = Paths.get("D:/", "temp", "a3.txt");
        if (!Files.exists(path2)) {
            Path filePath = Files.createFile(path2);
            //  D:\a3.txt
            System.out.println(filePath.toString());
        } else {
            System.out.println("a3.txt已存在");
        }

    }

    @Test
    public void exist() throws IOException {
        Path source = Paths.get("D:/temp/陈都灵.jpg");
        //文件不存在
        System.out.println("文件是否存在： " + Files.exists(source));
        //严格校验，文件是否存在
        boolean flag = Files.exists(source) && Files.isRegularFile(source);
        System.out.println("是文件，并且文件存在： " + flag);
    }

    /**
     * 复制文件
     */
    @Test
    public void f2() throws IOException {
        Path source = Paths.get("D:/temp/陈都灵.jpg");
        //创建目标文件夹
        Path targetDirPath = Files.createDirectories(Paths.get("D:/temp/C/"));
        //设置 目标文件路径
        Path target = Paths.get(targetDirPath.toString(), "陈都灵.jpg");
        //复制时，如果已存在，则替换
//        Path path = Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
        //方式2
//        if (Files.notExists(target)) {
//            Path path2 = Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);
//        }

    }

    /**
     * 写入到文件
     */
    @Test
    public void f3() throws Exception {
        Path path = Paths.get("C:\\Users\\cui\\Desktop\\4.txt");
        //创建文件并写入到文件
        Files.write(path, "神州载人飞船".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
    }


    /**
     * 遍历目录方法1
     */
    //a.log,contentType=null,contentType2=application/octet-stream
    //fonts.rar,contentType=null,contentType2=application/octet-stream
    //lyf.jpeg,contentType=image/jpeg,contentType2=image/jpeg
    //刘亦菲.jpeg,contentType=image/jpeg,contentType2=image/jpeg
    @Test
    public void f4() throws Exception {
        Path dirPath = Paths.get("D:\\360安全浏览器下载");
        Files.list(dirPath)
                .forEach(path -> {
                    //path.toString() = D:\360安全浏览器下载\a.log
                    //path.getFileName().toString() = a.log
                    String fileName = path.getFileName().toString();
                    try {
                        String contentType = Files.probeContentType(path);
                        String contentType2 = new MimetypesFileTypeMap().getContentType(fileName);
                        String contentType3 = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
                        System.out.println(fileName + ",  contentType=" + contentType + ",  contentType2=" + contentType2 + ",  contentType3=" + contentType3);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });

    }

    //遍历目录 方法2
    @Test
    public void f5() throws IOException {
        //newDirectoryStream list不会遍历子目录
        Path path = Paths.get("D:/");

        Files.newDirectoryStream(path)
                .forEach(x -> {
                    System.out.println(x.getFileName());
                });
    }

    //遍历目录 方法3  报错。
    @Test
    public void f6() throws IOException {
        //newDirectoryStream list不会遍历子目录
        Path path = Paths.get("D:/");
        List<Path> pathList = new LinkedList<Path>();
        Files.walkFileTree(path, new MySimpleFileVisitor(pathList))
                .forEach(x -> {
                    System.out.println(x.getFileName());
                });

    }

    /**
     * Files.isRegularFile(filePath)判断path是不是文件
     * Files.isDirectory(filePath)判断path是不是目录
     */
    @Test
    public void f7() throws Exception {
        Path dirPath = Paths.get("D:/", "temp", "A", "a.txt");
        Files.createDirectories(dirPath);//此时创建的 D:/temp/A/a.txt /就是目录

        Path dirPath2 = Paths.get("D:/", "temp");
        Path filePath = dirPath2.resolve("a.txt");
        Files.createFile(filePath);//此时创建爱你的D:/temp/a.txt 就是文件


        if (Files.exists(dirPath)) {
            System.out.println("D:\\temp\\A\\a.txt 存在");
        }

        if (Files.isDirectory(dirPath)) {
            System.out.println("D:\\temp\\A\\a.txt 是目录");
        } else {
            System.out.println("D:\\temp\\A\\a.txt 不是目录");
        }

        if (Files.isRegularFile(filePath)) {
            System.out.println("D:\\temp\\a.txt 是文件");
        } else {
            System.out.println("D:\\temp\\a.txt 不是文件");
        }
    }


    /**
     * 修改文件名
     */
    @Test
    public void move() throws Exception {
        Path dirPath = Paths.get("D:\\log");
        Files.list(dirPath)
                .forEach(sourcePath -> {
                    if (Files.isDirectory(sourcePath)) {
                        return;
                    }
                    Path parentPath = sourcePath.getParent();
                    String fileName = sourcePath.getFileName().toString();
                    int prefixIndex = fileName.lastIndexOf(".");
                    Path targetPath = Paths.get(parentPath.toString(), "AAA" + fileName.substring(0, prefixIndex) + fileName.substring(prefixIndex));
                    try {
                        Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });

    }
}
